<?php

namespace iBrand\Shop\Backend\Http\Controllers;

use iBrand\Component\Goods\Models\GoodsSpecRelation;
use iBrand\Component\Goods\Repositories\GoodsRepository;
use iBrand\Component\Purchase\Repositories\StockRecordRepository;
use iBrand\Shop\Backend\Model\TakeStockPlan;
use iBrand\Shop\Core\Models\TakeStockPlanItems;
use iBrand\Store\Backend\Model\SpecsValue;
use iBrand\Component\Goods\Models\GoodsProduct;

class PublicController extends Controller
{
    protected $goodsRepository;
    protected $stockRecordRepository;

    public function __construct(GoodsRepository $goodsRepository, StockRecordRepository $stockRecordRepository)
    {
        $this->goodsRepository = $goodsRepository;
        $this->stockRecordRepository = $stockRecordRepository;
    }

    public function goodsSelect()
    {
        $searchKey = request('searchKey');
        $limit = 10;
        $list = $this->goodsRepository->searchGoodsPaginate($searchKey, $limit);

        return response()->json(['optionList' => $list->toArray()]);
    }

    public function getStoredCount()
    {
        $goods_no = request('goods_no');
        $shop_id = request('shop_id') ? request('shop_id') : session('shop_id');
        $goods = $this->goodsRepository->getGoodsByGoodsNo($goods_no);
        $result = [];

        if ($goods) {
            foreach ($goods->hasManyProducts as $product) {
                $specID = $product->specID;
                $tmpSpec = SpecsValue::find($specID[0]);
                if ($tmpSpec->spec_id == 1) {
                    $size = $tmpSpec;
                    $color = SpecsValue::find($specID[1]);
                } elseif ($tmpSpec->spec_id == 2) {
                    $color = $tmpSpec;
                    $size = SpecsValue::find($specID[1]);
                }
                $colorName = GoodsSpecRelation::where('goods_id', $goods->id)->where('spec_value_id', $color->id)->first()->alias;

                $currentStock = $this->stockRecordRepository->getCurrentStock($shop_id, $product->id, GoodsProduct::class);

                $tmp = [
                    'id' => $product->id,
                    'goods_id' => $product->goods_id,
                    'sku' => $product->sku,
                    'colorId' => $color->id,
                    'colorName' => $colorName,
                    'sizeId' => $size->id,
                    'sizeName' => $size->name,
                    'number' => $currentStock,
                ];

                $result[] = $tmp;
            }
        }

        return $this->ajaxJson(true, $result);
    }
}